package com.gitee.funcy.multiple.datasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.gitee.funcy.multiple.datasource.datasource.DynamicDataSource;
import com.gitee.funcy.multiple.datasource.config.properties.AppDataSourceProperties;
import com.gitee.funcy.multiple.datasource.enums.DataSourceType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * druid 配置多数据源
 *
 * @author funcy
 */
@Slf4j
@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties("spring.datasource.druid.main")
    public DataSource mainDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 处理多数据源
     * @param appDataSourceProperties
     * @return
     */
    @Bean
    public Map<String, DataSource> appDataSourceMap(AppDataSourceProperties appDataSourceProperties) {
        LinkedHashMap<String, DataSource> appDataSourceMap = new LinkedHashMap<>();
        List<String> appDataSourceList = appDataSourceProperties.getDataSourceList();
        for(String dataSourceName : appDataSourceList) {
            log.info("创建app数据源：{}", dataSourceName);
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(appDataSourceProperties.getUrl(dataSourceName));
            dataSource.setUsername(appDataSourceProperties.getUsername(dataSourceName));
            dataSource.setPassword(appDataSourceProperties.getPassword(dataSourceName));
            appDataSourceMap.put(dataSourceName, dataSource);
        }
        return appDataSourceMap;
    }

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource mainDataSource, @Qualifier("appDataSourceMap") Map<String, DataSource> appDataSourceMap) {
        Map<Object, Object> targetDataSources = new HashMap<>(appDataSourceMap.size() + 1);
        targetDataSources.put(DataSourceType.main.name(), mainDataSource);
        targetDataSources.putAll(appDataSourceMap);
        return new DynamicDataSource(mainDataSource, targetDataSources);
    }

}
